﻿#region License
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MediaWiki.Common;

namespace MediaWiki.MediaWikiConverter.Utilities.Logging.Writers
{
  public abstract class LogWriterBase : ILogWriter
  {
    public bool WriteIndent { get; set; }
    public bool WriteTimeStamp { get; set; }
    public bool WriteCategories { get; set; }

    public abstract void Write(LogEntry logEntry);

    protected virtual string FormatMessage(LogEntry logEntry)
    {
      string message = logEntry.Message;
      DateTimeOffset timeStamp = logEntry.TimeStamp;
      ICollection<string> categories = logEntry.Categories;

      StringBuilder formattedMessage = new StringBuilder();
      int indentSize = 0;

      if (WriteTimeStamp)
      {
        string formattedTimeStamp = timeStamp.ToLocalTime().ToString("yyyy-MM-dd HH.mm.ss zzz");
        formattedMessage.Append(formattedTimeStamp);
        formattedMessage.Append(" - ");
      }

      if (WriteIndent)
      {
        indentSize += Logger.Context.IndentLevel * Logger.Context.IndentSize;
        indentSize += formattedMessage.Length;
      }

      if (WriteCategories)
      {
        string categoriesText = (categories == null || categories.Count == 0)
          ? string.Empty
          : string.Join(", ", categories.ToArray());

        message += categoriesText + " - " + message;
      }

      if (indentSize > 0)
      {
        message = message.Indent(indentSize);

        if (formattedMessage.Length > 0)
        {
          // remove time from first line
          message = message.Substring(formattedMessage.Length);
        }
      }

      formattedMessage.Append(message);

      return formattedMessage.ToString();
    }
  }
}